package com.vhall.component.framework.oss.client.impl.huawei;

import com.obs.services.ObsClient;
import com.obs.services.model.ObjectMetadata;
import com.obs.services.model.PutObjectResult;
import com.vhall.component.framework.oss.client.OssResult;
import com.vhall.component.framework.oss.client.impl.AbstractOssClient;
import com.vhall.component.framework.oss.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 华为云对象存储 客户端
 *
 * @author jingwen.li
 * @date 2023/2/22
 */
@Slf4j
public class HuaweiObsClient extends AbstractOssClient {

    // 创建ObsClient实例
    ObsClient obsClient = null;

    public HuaweiObsClient(OssProperties properties) {
        super(properties, new HuaweiObsCodeMapping());
    }

    @Override
    protected void doInit() {
        obsClient = new ObsClient(properties.getAppId(), properties.getSecretKey(), properties.getFullRegion());
    }

    @Override
    protected OssResult<String> doUpload(String name, String contentType, InputStream stream) throws IOException {
        String prefix = properties.getPrefix();
        String bucket = properties.getBucket();

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setCacheControl("no-cache");
        if (StringUtils.isNotEmpty(contentType)) {
            objectMetadata.setContentType(contentType);
        }
        String objectName = prefix + "/" + name;
        PutObjectResult putObjectResult = obsClient.putObject(bucket, objectName, stream, objectMetadata);

        return OssResult.build("OK", "success", "", properties.getCdnRegion() + "/" + putObjectResult.getObjectKey()
                , codeMapping);

    }
}
